package com.zz.cc.owner.app;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout.LayoutParams;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.zz.cc.owner.R;
import com.zz.cc.owner.data.Constants;
import com.zz.cc.owner.data.MyCarBrand;
import com.zz.cc.owner.data.MyCarModel;
import com.zz.cc.owner.util.PinyinComparator;
import com.zz.cc.owner.util.Util;
import com.zz.cc.owner.view.SideBar;
import com.zz.common.app.BaseActivity;

public class SelectCarToRegActivity extends OwnerBaseActivity implements OnClickListener{
	private ListView mListView;
	private MyAdapter mAdapter;
	private SideBar mSideBar;
	private TextView mDialogText;
	private List<MyCarBrand> mCarBrands = new LinkedList<MyCarBrand>();
	private List<MyCarModel> mCarModels = new LinkedList<MyCarModel>();
	private WindowManager mWindowManager;
	private Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case Constants.OWNER_REG_SUCCESS:
				dismissDialog();
				showWaitDialog("注册成功，为你自动登录中...", false);
				sendEmptyMessageDelayed(Constants.LOGIN_SUCCESS, 1500);
				break;
			case Constants.LOGIN_SUCCESS:
				dismissDialog();
				startActivity(new Intent(SelectCarToRegActivity.this, NewMainActivity.class));
				finish();
				break;
			case Constants.LOGIN_FAILED:
				Util.showToast(SelectCarToRegActivity.this, "自动登录失败，请手动登录");
				dismissDialog();
				startActivity(new Intent(SelectCarToRegActivity.this, LoginActivity.class));
				finish();
				break;
			case Constants.OWNER_REG_FAILED:
				dismissDialog();
				Util.showToast(SelectCarToRegActivity.this, "注册失败，请重试");
				break;
			default:
				break;
			}
		};
	};
	//模拟生成车品牌和车数据
	private void emulateDatas(){
		MyCarBrand honda_brand = new MyCarBrand();
		honda_brand.id = 1;
		honda_brand.brandName = "本田";
		mCarBrands.add(honda_brand);
		MyCarBrand bmw_brand = new MyCarBrand();
		bmw_brand.id = 2;
		bmw_brand.brandName = "本田";
		mCarBrands.add(bmw_brand);
		MyCarBrand benz_brand = new MyCarBrand();
		benz_brand.id = 3;
		benz_brand.brandName = "奔驰";
		mCarBrands.add(benz_brand);
		MyCarBrand audi_brand = new MyCarBrand();
		audi_brand.id = 4;
		audi_brand.brandName = "奥迪";
		mCarBrands.add(audi_brand);
		MyCarBrand aston_brand = new MyCarBrand();
		aston_brand.id = 5;
		aston_brand.brandName = "丰田";
		mCarBrands.add(aston_brand);
		//模拟车型
		MyCarModel accord_model = new MyCarModel();
		accord_model.id = 1;
		accord_model.modelName = "本田雅阁";
		accord_model.brand = honda_brand;
		mCarModels.add(accord_model);
		MyCarModel fit_model = new MyCarModel();
		fit_model.id = 2;
		fit_model.modelName = "本田飞度";
		fit_model.brand = honda_brand;
		mCarModels.add(fit_model);
		
		MyCarModel bmw5_model = new MyCarModel();
		bmw5_model.id = 3;
		bmw5_model.modelName = "宝马5系";
		bmw5_model.brand = bmw_brand;
		mCarModels.add(bmw5_model);
		
		MyCarModel bmw7_model = new MyCarModel();
		bmw7_model.id = 4;
		bmw7_model.modelName = "宝马7系";
		bmw7_model.brand = bmw_brand;
		mCarModels.add(bmw7_model);
		
		MyCarModel benzs_model = new MyCarModel();
		benzs_model.id = 5;
		benzs_model.modelName = "奔驰S系";
		benzs_model.brand = benz_brand;
		mCarModels.add(benzs_model);
		
		MyCarModel benze_model = new MyCarModel();
		benze_model.id = 6;
		benze_model.modelName = "奔驰E系";
		benze_model.brand = benz_brand;
		mCarModels.add(benze_model);
		
		
		MyCarModel audia6_model = new MyCarModel();
		audia6_model.id = 7;
		audia6_model.modelName = "奥迪A6";
		audia6_model.brand = audi_brand;
		mCarModels.add(audia6_model);
		
		MyCarModel audia4_model = new MyCarModel();
		audia4_model.id = 8;
		audia4_model.modelName = "奥迪A4";
		audia4_model.brand = audi_brand;
		mCarModels.add(audia4_model);
		
		MyCarModel astongt_model = new MyCarModel();
		astongt_model.id = 9;
		astongt_model.modelName = "丰田凯美瑞";
		astongt_model.brand = aston_brand;
		mCarModels.add(astongt_model);
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		emulateDatas();
		initUI();
	}
	private void initUI(){
		setContentView(R.layout.selectcartoreg);
		((TextView)findViewById(R.id.titleTextView)).setText("选择车型");
		findViewById(R.id.backImg).setOnClickListener(this);
		mListView = (ListView)findViewById(R.id.lvContact);
		mListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				showWaitDialog("注册中，请稍候...", true);
				mHandler.sendEmptyMessageDelayed(Constants.OWNER_REG_SUCCESS, 2000);
			}
		});
		mAdapter = new MyAdapter(this);
		mListView.setAdapter(mAdapter);
		mSideBar = (SideBar) findViewById(R.id.sideBar);
		mSideBar.setListView(mListView);
		mDialogText = (TextView) LayoutInflater.from(this).inflate(
				R.layout.sidebar_item, null);
		mDialogText.setVisibility(View.INVISIBLE);
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_APPLICATION,
				WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
						| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
				PixelFormat.TRANSLUCENT);
		mWindowManager.addView(mDialogText, lp);
		mSideBar.setTextView(mDialogText);
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.backImg:
			finish();
			break;

		default:
			break;
		}
	}
	class MyAdapter extends BaseAdapter implements SectionIndexer {
		private Context mContext;
		private boolean mShowCheckbox;
		public MyAdapter(Context mContext) {
			this.mContext = mContext;
			doSort();
		}

		public void doSort() {
			Collections.sort(mCarModels, new PinyinComparator());
		}

		@Override
		public int getCount() {
			return mCarModels.size();
		}

		public void showCheckbox(boolean show) {
			this.mShowCheckbox = show;
		}

		@Override
		public MyCarModel getItem(int position) {
			return mCarModels.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			MyCarModel model = mCarModels.get(position);
			final String nickName = model.modelName.trim();
			ViewHolder viewHolder = null;
			if (convertView == null) {
				convertView = LayoutInflater.from(mContext).inflate(
						R.layout.selectcartoreg_item, null);
				viewHolder = new ViewHolder();
				viewHolder.tvCatalog = (TextView) convertView
						.findViewById(R.id.contactitem_catalog);
				viewHolder.tvNick = (TextView) convertView
						.findViewById(R.id.contactitem_nick);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			String catalog = converterToFirstSpell(nickName).substring(0,1);
			if (position == 0) {
				viewHolder.tvCatalog.setVisibility(View.VISIBLE);
				viewHolder.tvCatalog.setText(catalog);
			} else {
				String lastCatalog = converterToFirstSpell(
						mCarModels.get(position - 1).modelName).substring(0,1);
				if (!catalog.equalsIgnoreCase(lastCatalog)) {
					viewHolder.tvCatalog.setVisibility(View.VISIBLE);
					viewHolder.tvCatalog.setText(catalog);
					
				} else {
					viewHolder.tvCatalog.setVisibility(View.GONE);
				}
			}
			
			
			
			
			viewHolder.tvNick.setText(nickName);
			return convertView;
		}

		class ViewHolder {
			TextView tvCatalog;// 目录
			TextView tvNick;
		}

		@Override
		public int getPositionForSection(int section) {
			for (int i = 0; i < mCarModels.size(); i++) {
				String l = converterToFirstSpell(mCarModels.get(i).brand.brandName)
						.trim();
				char firstChar = l.toUpperCase().charAt(0);
				if (firstChar == section) {
					return i;
				}
			}
			return -1;
		}

		@Override
		public int getSectionForPosition(int position) {
			return 0;
		}

		@Override
		public Object[] getSections() {
			return null;
		}
	}
	public static String converterToFirstSpell(String chines) {
		String pinyinName = "";
		char[] nameChar = chines.toCharArray();
		HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
		defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
		defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		for (int i = 0; i < nameChar.length; i++) {
			if (nameChar[i] > 128) {
				try {
					pinyinName += PinyinHelper.toHanyuPinyinStringArray(
							nameChar[i], defaultFormat)[0].charAt(0);
				} catch (BadHanyuPinyinOutputFormatCombination e) {
					e.printStackTrace();
				}
			} else {
				pinyinName += nameChar[i];
			}
		}
		return pinyinName;
	}
}
